package com.stanwind.api;

import com.stanwind.constant.ServerSetting;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

@Component
public class TokenUtils {
    @Autowired
    private NumberUtils numberUtils;

    @Autowired
    private RedisUtils redisUtils;

    // todo:生成token
    public String generateToken(String accountId) {
        String nowTime = System.currentTimeMillis() + ServerSetting.TOKENKEY;
        String token = numberUtils.MD5(numberUtils.MD5(accountId + nowTime));

        Jedis jedis = redisUtils.getJedisObject();
        //先查看accountId是否存在
        String tempToekn = this.getTokenByAccountId(accountId);
        deleteToken(tempToekn);

        Transaction transaction = jedis.multi();
        transaction.set(token, accountId);
        transaction.set(accountId, token);
        transaction.exec();

        redisUtils.expire(token, ServerSetting.EXPIRE_TIME);
        redisUtils.expire(accountId, ServerSetting.EXPIRE_TIME);

        redisUtils.recycleJedisOjbect(jedis); // 将 获取的jedis实例对象还回池中

        return token;
    }

    // todo:验证token是否有效
    public boolean checkToken(String token) {
        boolean flag = false;
        flag = redisUtils.checkExpire(token) && redisUtils.checkExpire(this.getAccountIdByToken(token));
        //flag=true;
        return flag;
    }

    // todo:将token有效期延期，token默认有效期为7天，当天操作过token将有效期延期一天
    public boolean delayTokenDeadline(String token) {
        boolean flag = false;
        redisUtils.expire(token, ServerSetting.EXPIRE_TIME);
        redisUtils.expire(this.getAccountIdByToken(token), ServerSetting.EXPIRE_TIME);
        return flag;
    }

    // todo:清除token
    public boolean deleteToken(String token) {
        boolean flag = false;
        redisUtils.deleteByKey(this.getAccountIdByToken(token));
        redisUtils.deleteByKey(token);
        return flag;
    }

    /**
     * 根据访问的token返回账号
     *
     * @param token 鉴权token
     * @return 绑定的账号
     */
    public String getAccountIdByToken(String token) {
        Jedis jedis = redisUtils.getJedisObject();
        String account = jedis.get(token);
        redisUtils.recycleJedisOjbect(jedis); // 将 获取的jedis实例对象还回池中
        return account == null ? "" : account;
    }

    /**
     * 通过访问的accountId返回token
     *
     * @param accountId
     * @return token
     */
    public String getTokenByAccountId(String accountId) {
        Jedis jedis = redisUtils.getJedisObject();
        String token = jedis.get(accountId);
        redisUtils.recycleJedisOjbect(jedis); // 将 获取的jedis实例对象还回池中
        return token == null ? "" : token;
    }

//	public static void main(String[] args) {
//		// TODO Auto-generated method stub
//		System.out.println(generateToken("15201633796"));
//		System.out.println(MD5.check(MD5.encodeString("15201633796"),
//				generateToken("15201633796")));
//	}

}
